package 算法.leetcode.linked.list;

/**
 * @author lchenglong
 * @date 2020/11/30
 */
public class AddTwoNumbers {

    public static class ListNode {

        int val;

        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }


        public void out(ListNode listNode) {
            StringBuilder stringBuilder = new StringBuilder();
            while (listNode!=null) {
                stringBuilder.append(listNode.val).append("-->");
                listNode = listNode.next;
            }
            System.out.println(stringBuilder.toString());
        }
    }

    public static void main(String[] args) {
        AddTwoNumbers instance = new AddTwoNumbers();
        ListNode l1 = new ListNode(2);
        ListNode l = l1;
        ListNode listNode = new ListNode(4);
        l1.next = listNode;
        l1 = l1.next;
        listNode = new ListNode(9);
        l1.next = listNode;

        ListNode l2 = new ListNode(5);
        ListNode l21 = new ListNode(6);
        l2.next = l21;
        ListNode l22 = new ListNode(4);
        l21.next = l22;
        ListNode l23 = new ListNode(9);
        l22.next = l23;
        ListNode result = instance.addTwoNumbers(l, l2);
        result.out(result);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = l1;
        ListNode tail = null;
        int h = 0;
        for (; l1 != null; l1=l1.next) {
            int sum = 0;
            sum += l1.val;
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            if (h > 0) {
                sum += h;
                h = 0;
            }
            if (sum >= 10) {
                sum -= 10;
                h = 1;
            }
            l1.val = sum;
            if (l1.next == null) {
                tail = l1;
            }
        }
        if (l1 == null ){
            l1 = tail;
        }
        while (l2!=null) {
            l1.next = l2;
            int val = l2.val + h;
            h=0;
            if (val >=10) {
                l2.val = 0;
                h =1;
            }
            if (l2.next == null) {
                tail = l2;
            }
            l2 = l2.next;
        }
        if (h>0){
            ListNode listNode = new ListNode(h);
            l1.next = listNode;
        }
        return result;
    }
}
